# -*- coding;utf-8 -*-
"""
File name : SettleBankPointAndDownloadWithQuestionList.PY
Program IDE : PyCharm
Create file time: 2023/10/20 10:26
File Create By Author : 朱清闯
"""
from question.models import DownloadQuestionLog
from django.conf import settings
from account.models import User


def search_receiver(bank_point_change_this, item):
    position = -1
    for i in range(len(bank_point_change_this)):
        if bank_point_change_this[i]['receiver'] == item['owner']['id']:
            # bank_point_change_this[i]['point_amount'] += item['bank_point']
            position = i
            break
    return position


# 根据题目列表，结算本次下载题目的总金额和下载次数；即新建本次新下载记录和本次题目拥有者列表，持久化到数据库,sum_point下载所需总库币
def settle_bank_point_and_download_question(question_list, user):
    sum_point = 0
    download_this_new = []
    bank_point_change_this = []
    download_history = DownloadQuestionLog.objects.filter(user__id=user.id)
    company_account = User.objects.filter(username=settings.COMPANY['president']).first()
    if download_history:
        download_history = download_history.values('question')
    for item in question_list:
        # 用户自己的题目，不计入结算费用
        if item['owner']['id'] == user.id:
            continue
        # 该用户有过下载记录，且本次下载到题目不在下载记录中，且试题不免费，则创建下载记录和结算金额
        if len(download_history) > 0 and item['id'] not in download_history and item['bank_point'] > 0:
            download_this_new.append(item)
            sum_point += item['bank_point']
            # 如果被下载者第一次出现，则加在尾部；否则查找在打款记录的位置，累加库币值
            position = search_receiver(bank_point_change_this, item)
            if position == -1:
                bank_point_change_this.append({'operator': company_account,
                                               'receiver': item['owner']['id'],
                                               'point_amount': item['bank_point']})
            else:
                bank_point_change_this[position]['point_amount'] += item['bank_point']
        # 免费试题，只创建下载记录
        if len(download_history) > 0 and item not in download_history and item['bank_point'] <= 0:
            download_this_new.append(item)
        # 该用户未下载过题目， 且本试题不免费，则创建下载记录且创建结算金额
        if len(download_history) == 0 and item['bank_point'] > 0:
            download_this_new.append(item)
            sum_point += item['bank_point']
            # 同上
            position = search_receiver(bank_point_change_this, item)
            if position == -1:
                bank_point_change_this.append({'operator': company_account,
                                               'receiver': item['owner']['id'],
                                               'point_amount': item['bank_point']})
            else:
                bank_point_change_this[position]['point_amount'] += item['bank_point']
        if not download_history and item['bank_point'] <= 0:
            download_this_new.append(item)
    return bank_point_change_this, download_this_new, sum_point


